//
//  StatusCell.swift
//  LVWeibo
//
//  Created by lv on 15/6/30.
//  Copyright © 2015年 lv. All rights reserved.
//

import UIKit
import FFAutoLayout
import SDWebImage

/// 转发微博 cell
let WBStatusForwardCellIdentifier = "WBStatusForwardCellIdentifier"
/// 原创微博 cell
let WBStatusNormalCellIdentifier = "WBStatusNormalCellIdentifier"
// 图片视图可重用标示符
private let WB_PictureReusableIdentifier = "PictureCell"
// 屏幕宽度
private let screenWidth = UIScreen.mainScreen().bounds.width

// cell的代理方法
protocol StatusCellDelegate: NSObjectProtocol {
    func statusCellDidSelectedPhoto(cell: StatusCell,photoIndex: Int)
}

class StatusCell: UITableViewCell,UICollectionViewDataSource,UICollectionViewDelegate {
    
    // 设置代理属性
    weak var photoDelegate: StatusCellDelegate?
    
    /// 转发微博标签
    var forwardLabel: UILabel?
    
    /// 配图视图宽高约束
    var widthCons: NSLayoutConstraint?
    var heightCons: NSLayoutConstraint?
    
    /// 微博模型数据
    var status: Status? {
        didSet {
            // 用户头像
            iconView.sd_setImageWithURL(status?.user?.profile_URL)
            // 名称
            nameLable.text = status?.user?.name
            // 发送时间
            timeLable.text = NSDate.sinaDateWithString(status?.created_at ?? "").dateDescription()
            // 微博来源
            sourceLabel.text = status?.source
            
            // 文本内容
            contentLable.attributedText = EmoticonPackage.emoticonAttributeString(status?.text ?? "", font: contentLable.font)
            // 认证图标
            verifiedView.image = status?.user?.verified_image
            // 会员图标
            memberView.image = status?.user?.mbImage
            // 转发微博文字
            let forwardText = "@" + (status?.retweeted_status?.user?.name ?? "") + ": " + (status?.retweeted_status?.text ?? "")
            
            forwardLabel?.attributedText = EmoticonPackage.emoticonAttributeString(forwardText, font: contentLable.font)
            
            
            // 设置配图视图宽高
            let size = calcPictureSize(status!)
            widthCons?.constant = size.width
            heightCons?.constant = size.height
            
            // 刷新数据
            picturesView.reloadData()
        }
    }
    
    //MARK:- cell的可重用标示符
    class func cellIdentifier(status: Status) -> String {
        return status.retweeted_status == nil ? WBStatusNormalCellIdentifier : WBStatusForwardCellIdentifier
    }
    
    //MARK:- 计算行高
    func rowHeight(status: Status) -> CGFloat {
        self.status = status
        layoutIfNeeded()
        return CGRectGetMaxY(footerView.frame)
    }
    
    //MARK:- 初始化自定义cell,自动布局
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        // 取消cell选中的高亮状态
        selectionStyle = UITableViewCellSelectionStyle.None
        
        // 添加顶部间隔视图
        let topView = UIView()
        topView.backgroundColor = UIColor(white: 0.95, alpha: 0.5)
        addSubview(topView)
        topView.ff_AlignInner(ff_AlignType.TopCenter, referView: self, size: CGSize(width: screenWidth, height: 10), offset: CGPointZero)
        
        // 添加底部视图上方分割线
        let lineView = UIView()
        lineView.backgroundColor = UIColor(white: 0.95, alpha: 0.5)
        addSubview(lineView)
        
        /// 添加子控件
        addSubview(iconView)
        addSubview(nameLable)
        addSubview(memberView)
        addSubview(verifiedView)
        addSubview(timeLable)
        addSubview(sourceLabel)
        addSubview(contentLable)
        addSubview(picturesView)
        addSubview(footerView)
        
        // 自动布局
        // 头像
        iconView.ff_AlignVertical(ff_AlignType.BottomLeft, referView: topView, size: CGSize(width: 35, height: 35), offset: CGPoint(x: 12, y: 12))
        // 友好显示名称
        nameLable.ff_AlignHorizontal(ff_AlignType.TopRight, referView: iconView, size: nil, offset: CGPoint(x: 12, y: 0))
        // 会员图像
        memberView.ff_AlignHorizontal(ff_AlignType.TopRight, referView: nameLable, size: nil, offset: CGPoint(x: 5, y: 0))
        // 认证图像
        verifiedView.ff_AlignInner(ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: 6, y: 6))
        // 时间标签
        timeLable.ff_AlignHorizontal(ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPoint(x: 12, y: 0))
        // 来自标签
        sourceLabel.ff_AlignHorizontal(ff_AlignType.BottomRight, referView: timeLable, size: nil, offset: CGPoint(x: 12, y: 0))
        // 文本内容
        contentLable.ff_AlignVertical(ff_AlignType.BottomLeft, referView: iconView, size: nil, offset: CGPoint(x: 0, y: 12))
        
        // 底部视图
        footerView.ff_AlignVertical(ff_AlignType.BottomLeft, referView: lineView, size: CGSize(width: screenWidth, height: 25), offset: CGPoint(x: -12, y: 8))
        // 底部视图上方分割线
        lineView.ff_AlignInner(ff_AlignType.BottomLeft, referView: picturesView, size: CGSize(width: screenWidth, height: 1), offset: CGPoint(x: -12, y: 8))
        
        // 设置配图视图
        preparePictureView()
        
    }
    
    //MARK:- 设置配图视图
    private func preparePictureView() {
        picturesView.registerClass(StatusPictureCell.self, forCellWithReuseIdentifier: WB_PictureReusableIdentifier)
        picturesView.dataSource = self
        // 设置配图视图的代理
        picturesView.delegate = self
        picturesView.backgroundColor = UIColor.whiteColor()
    }
    
    //MARK:- UICollectionView的代理方法-选中照片
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let cell = collectionView.cellForItemAtIndexPath(indexPath) as! StatusPictureCell
        let url = status!.middlePicURLs![indexPath.item]
        
        SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: { (current, total) -> Void in
                    cell.iconView.progress = CGFloat(current) / CGFloat(total)
            }, completed: { (_, error, _, _, _) -> Void in
                print(error)
                cell.iconView.progress = 0
                // 需要tableView modal出一个控制器
                self.photoDelegate?.statusCellDidSelectedPhoto(self, photoIndex: indexPath.item)
            })
    }
    
    
    // MARK:- UICollectionView数据源方法
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.picURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(WB_PictureReusableIdentifier, forIndexPath: indexPath) as! StatusPictureCell
        cell.imageURL = status!.picURLs![indexPath.item]
        return cell
    }
    
    //MARK:- 计算配图视图大小
    private func calcPictureSize(status: Status) ->CGSize {
        
        let count = status.picURLs?.count ?? 0
        if count == 0 {
            return CGSizeZero
        }
        if count == 1 {
            // 获取缓存图片
            // 图片完成路径
            let key = status.picURLs![0].absoluteString
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            layout.itemSize = image.size
            return layout.itemSize
        }
        let itemsize = CGSize(width: 90, height: 90)
        let margin: CGFloat = 5
        layout.itemSize = itemsize
        layout.minimumInteritemSpacing = margin
        layout.minimumLineSpacing = margin
        
        if count == 4 {
            return CGSizeMake(2 * itemsize.width + margin, 2 * itemsize.height + margin)
        }
        // 多张照片
        // 每行图片数量
        let rowCount =  3
        // 行号
        let row = (count - 1) / rowCount + 1
        let w = itemsize.width * CGFloat(rowCount) + CGFloat(rowCount - 1) * margin
        let h = itemsize.height * CGFloat(row) + CGFloat(row - 1) * margin
        return CGSize(width: w, height: h)
    }
    
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //MARK:- 懒加载子控件
    /// 用户头像
    lazy var iconView: UIImageView = UIImageView()
    /// 友好显示名称
    lazy var nameLable: UILabel = UILabel(textColor: UIColor.darkGrayColor(), fonSize: 14,layoutWidth: 0)
    /// 会员图像
    lazy var memberView: UIImageView = UIImageView()
    /// 认证图像
    lazy var verifiedView: UIImageView = UIImageView()
    /// 时间标签
    lazy var timeLable: UILabel = UILabel(textColor: UIColor.orangeColor(), fonSize: 10,layoutWidth: 0)
    /// 来自标签
    lazy var sourceLabel: UILabel = UILabel(textColor: UIColor.darkGrayColor(), fonSize: 10,layoutWidth: 0)
    /// 内容文字
    lazy var contentLable: UILabel = UILabel(textColor: UIColor.darkGrayColor(), fonSize: 14, layoutWidth: screenWidth - 20)
    
    ///  添加 CollectionView 作为配图视图
    // 布局
    lazy var layout = UICollectionViewFlowLayout()
    // 配图(声明类型)
    lazy var picturesView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.layout)
    
    // 底部视图
    lazy var footerView: StatusFooterView = StatusFooterView()
}

//MARK:- 显示配图视图
private class StatusPictureCell: UICollectionViewCell {
    
    var imageURL: NSURL? {
        didSet {
            // 设置进度初始值
            iconView.progress = 0
            
            // 如果本地有`缓存`，直接加载本地缓存的图片，如果没有，会自动下载
            iconView.sd_setImageWithURL(imageURL!)
            
            // 设置gif的是否显示
            gifView.hidden = !(imageURL!.absoluteString.pathExtension.lowercaseString == "gif")
        }
    }
    var iconView: LVImageView = LVImageView()
    // gifView
    lazy var gifView: UIImageView = {
        let gifView = UIImageView()
        gifView.image = UIImage(named: "timeline_image_gif")
        return gifView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        // 设置图片显示填充模式，等比例填充，需要裁切
        iconView.contentMode = UIViewContentMode.ScaleAspectFill
        iconView.clipsToBounds = true
        
        addSubview(iconView)
        iconView.ff_Fill(self)
        addSubview(gifView)
        
        // 布局
        gifView.ff_AlignInner(ff_AlignType.BottomRight, referView: self, size: nil)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
//MARK:- 底部视图
class StatusFooterView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.backgroundColor = UIColor(white: 1.0, alpha: 1.0)
        addSubview(forwardButton)
        addSubview(commontButton)
        addSubview(likeButton)
        
        ff_HorizontalTile([forwardButton,commontButton,likeButton], insets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0))
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 懒加载底部按钮
    lazy var forwardButton: UIButton = UIButton(btnTitle: "转发", imageName: "timeline_icon_retweet", fontSize: 12)
    lazy var commontButton: UIButton = UIButton(btnTitle: "评论", imageName: "timeline_icon_comment", fontSize: 12)
    lazy var likeButton: UIButton = UIButton(btnTitle: "赞", imageName: "timeline_icon_unlike", fontSize: 12)
}
